export const handleTree = tree => {
  tree.forEach(item => {
    if (item.loading === true) {
      delete item.loading
    }
    if (item.loading === null) {
      delete item.loading
    }
    if (item.children === null) {
      item.children = []
    }
    if (item.children) {
      handleTree(item.children)
    }
  })
}

export const recursion = {
  convertTreeShow: function (tree, choosedArr) {
    const result = []
    tree.forEach(item => {
      // 读取 map 的键值映射
      const expand = true
      const title = item.title
      const code = item.code
      let checked = false
      const disabled = true
      const disableCheckbox = true
      for (let i = 0; i < choosedArr.length; i++) {
        if (item.code === choosedArr[i]) {
          checked = true
        }
      }
      let children = item.children
      if (children) {
        // 如果有子节点，递归
        children = this.convertTreeShow(children, choosedArr)
      }
      result.push({ expand, code, checked, disabled, disableCheckbox, title, children })
    })
    return result
  },

  convertTreeEdit: function (tree, choosedArr, type) {
    const result = []
    tree.forEach(item => {
      // 读取 map 的键值映射
      const expand = true
      const title = item.title
      const code = item.code
      const level = item.level
      const disabled = type
      let checked = false
      for (let i = 0; i < choosedArr.length; i++) {
        if (item.code === choosedArr[i]) {
          checked = true
        }
      }
      let children = item.children
      if (children) {
        // 如果有子节点，递归
        children = this.convertTreeEdit(children, choosedArr, type)
      }
      result.push({ expand, code, checked, title, children, level, disabled })
    })
    return result
  },

  convertTreeAdd: function (tree, type) {
    const result = []
    tree.forEach(item => {
      // 读取 map 的键值映射
      const code = item.code
      const title = item.title
      const level = item.level
      let expand
      if (item.level === type) {
        expand = true
      } else {
        expand = false
      }
      const checked = false
      let children = item.children
      if (children) {
        // 如果有子节点，递归
        children = this.convertTreeAdd(children, type)
      }
      result.push({ code, title, expand, checked, children, level })
    })
    return result
  },

  convertTree: function (tree, map) {
    const result = []
    tree.forEach(item => {
      // 读取 map 的键值映射
      const value = item[map.value]
      const label = item[map.label]
      const level = item[map.level]
      const loading = map.loading
      let children = item[map.children] || []
      // 如果有子节点，递归
      if (children && children.length) {
        children = recursion.convertTree(children, map)
      }

      const resItem = {
        value,
        label
      }
      if (Object.keys(map).includes('children')) resItem.children = children
      if (Object.keys(map).includes('level')) resItem.level = level
      if (Object.keys(map).includes('loading')) resItem.loading = loading
      result.push(resItem)
    })
    return result
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export const formatTimes = {
  formatTime: function (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  },
  formatHMS: function (date) {
    const hour = date.getHours()
    const minute = date.getMinutes()
    // const second = date.getSeconds()
    return [hour, minute].map(formatNumber).join(':')
  },
  formatDate: function (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(formatNumber).join('-')
  },
  formatDateCN: function (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return year + '年' + formatNumber(month) + '月' + formatNumber(day) + '日'
  },
  formatWeek: function (date) {
    const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekKey = date.getDay()
    return week[weekKey]
  },
  formatDuration: function (duration) {
    let second
    let minute
    let hour
    hour = Math.floor(duration / 3600) % 24 // 转小时
    minute = Math.floor((duration / 60) % 60) // 转分钟
    second = Math.floor(duration % 60) // 转秒
    // 格式化
    hour = (hour > 9 ? hour : '0' + hour) + ''
    minute = (minute > 9 ? minute : '0' + minute) + ''
    second = (second > 9 ? second : '0' + second) + ''
    return hour + ':' + minute + ':' + second
  },
  formatTimestamp: function (duration) {
    const hour = duration.split(':')[0]
    const min = duration.split(':')[1]
    const sec = duration.split(':')[2]
    return (Number(hour * 3600) + Number(min * 60) + Number(sec)) * 1000
  }
}

export const checkDate = dateStr => {
  const ymd = /^(\d{4})-(\d{2})-(\d{2})$/
  if (!ymd.test(dateStr)) {
    return false
  }
  return true
}

export const imageCompress = {
  // 压缩图片
  compress(img) {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const tCanvas = document.createElement('canvas')
    const tctx = tCanvas.getContext('2d')
    // let initSize = img.src.length;
    let width = img.width
    let height = img.height
    let ratio
    if ((ratio = (width * height) / 4000000) > 1) {
      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      ratio = Math.sqrt(ratio)
      width /= ratio
      height /= ratio
    } else {
      ratio = 1
    }
    canvas.width = width
    canvas.height = height
    //    铺底色
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    // 如果图片像素大于100万则使用瓦片绘制
    let count
    if ((count = (width * height) / 1000000) > 1) {
      // 计算要分成多少块瓦片
      count = ~~(Math.sqrt(count) + 1)
      // 计算每块瓦片的宽和高
      const nw = ~~(width / count)
      const nh = ~~(height / count)
      tCanvas.width = nw
      tCanvas.height = nh
      for (let i = 0; i < count; i++) {
        for (let j = 0; j < count; j++) {
          tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
          ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
        }
      }
    } else {
      ctx.drawImage(img, 0, 0, width, height)
    }
    // 进行最小压缩
    const ndata = canvas.toDataURL('image/jpeg', 0.1)
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
    return ndata
  },
  dataURLtoFile(dataurl, filename) {
    // 将base64转换为文件
    var arr = dataurl.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    var bstr = atob(arr[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, {
      type: mime
    })
  }
}

export const toChinesNum = num => {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['', '十', '百', '千', '万']
  num = parseInt(num)
  const getWan = temp => {
    const strArr = temp.toString().split('').reverse()
    let newNum = ''
    for (var i = 0; i < strArr.length; i++) {
      if ((!i && !strArr[i]) || (i > 0 && !strArr[i] && !strArr[i - 1])) {
        newNum = ''
      } else {
        newNum = changeNum[strArr[i]] + (!strArr[i] ? unit[0] : unit[i]) + newNum
      }
    }
    return newNum
  }
  const overWan = Math.floor(num / 10000)
  let noWan = num % 10000
  if (noWan.toString().length < 4) noWan = '0' + noWan
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler)
      }
    }
  }
})()
